package com.onion.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class HttpDownloader {

    private Logger logger = LoggerFactory.getLogger(HttpDownloader.class);

    /**
     * 下载文件至本地
     * @param srcUrl
     * @param filePath
     */
    public void download(String srcUrl, String filePath){
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            httpGet = new HttpGet(srcUrl);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                byte[] byteData = readInputStream(inputStream);
                File file = new File(filePath);
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(byteData);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try{
            while((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        }finally {
            bos.close();
        }
    }

}